package com.kstudio.videocapture.listfile;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.kstudio.videocapture.KVideoCapture;
import com.kstudio.videocapture.R;
import com.kstudio.videocapture.editimage.KImageEditActivity;
import com.kstudio.videocapture.editvideo.KVideoEditActivity;
import com.kstudio.videocapture.listfile.KFileListAdapterWrapper.KFileListCheckClickListener;
import com.kstudio.videocapture.listfile.fileaction.KFileActionUtil;
import com.kstudio.videocapture.listimage.KImageListActivity;
import com.kstudio.videocapture.util.KLog;
import com.kstudio.videocapture.util.KhFile;
import com.kstudio.videocapture.util.KhProgressDialog;

public class KFileListActivity extends Activity {
    private final KLog log = new KLog("KFileList");

    private static final int            MENU_MODE_LIST      = 0x0001;
    private static final int            MENU_MODE_COPY      = 0x0002;
    private static final int            MENU_MODE_MOVE      = 0x0003;
    private static final int            MENU_MODE_DELETE    = 0x0004;

    private static final int            REQUEST_CODE_COPY   = MENU_MODE_COPY;
    private static final int            REQUEST_CODE_MOVE   = MENU_MODE_MOVE;

    private KVideoCapture mApplication;
    private Context       mContext;

    private Menu                        mMenu;
    private int							mMenuMode;
    private boolean                     mMenuCheckAll;
    private MenuItem                    mMenuDone;

    private ListView                    mListView;
    private ArrayList<KFileListItem>    mFileList;
    private KFileListAdapter            mAdapter;

    private KhProgressDialog            mProgressDialog;

    private String                      mCurrentpath;
    private int                         mIconWidth;
    private int                         mIconHeight;

    private File                        mSdCard;
    private File                        mExtsdCard;
    private String                      mRoot = "..";

    private int                         mContextMenuPos;
    private Handler                     mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgressDialog.setTitle(String.format("prg = %s", 1));
            mProgressDialog.setProgress(1);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        log.i("***************** KFileListActivity onCreate *****************");
        super.onCreate(savedInstanceState);

        setContentView(R.layout.file_list_activity);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        mMenuMode = MENU_MODE_LIST;
        mMenu = null;
        mMenuDone = null;

        init();
    }

    @Override
    protected void onResume() {
        log.i("***************** KFileListActivity onResume *****************");
        mCurrentpath = makeFileList(mCurrentpath);

        super.onResume();
    }

    @Override
    protected void onPause() {
        log.i("***************** KFileListActivity onPause *****************");

        mAdapter.stop();

        super.onPause();
    }

    @Override
    protected void onStop() {
        log.i("***************** KFileListActivity onStop *****************");

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        log.i("***************** KFileListActivity onDestroy *****************");

        super.onDestroy();
    }

    /* Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenu = menu;
        getMenuInflater().inflate(R.menu.activity_filelist, mMenu);
        return true;
    }

    /* Event */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                if(mCurrentpath.equals(mRoot)) {
                    finish();
                } else if(mCurrentpath.equals(mSdCard.getPath()) || (mExtsdCard == null ? false : mCurrentpath.equals(mExtsdCard.getPath()))) {
                    mCurrentpath = makeFileList(mRoot);
                } else {
                    char separatorChar = System.getProperty("file.separator", "/").charAt(0);
                    int separatorIndex = mCurrentpath.lastIndexOf(String.valueOf(separatorChar));

                    if(separatorIndex > 0)
                        mCurrentpath = makeFileList(mCurrentpath.substring(0, separatorIndex));
                }
            return true;

            case R.id.menu_repository :
            {
                Intent intent = new Intent(mContext, KImageListActivity.class);
                intent.putExtra("ImageListMode", KImageListActivity.IMAGELIST_MODE_GRID);
                startActivity(intent);
            }
            return true;

            case R.id.menu_filelist_copy :
                mMenuMode = MENU_MODE_COPY;
                mMenuCheckAll = false;
                mAdapter.fileCheckEnable(KFileListAdapter.MODE_CHECK);
                for(KFileListItem fileitem: mFileList) {
                    fileitem.setFileCheck(false);
                }
                mAdapter.notifyDataSetChanged();
            return true;

            case R.id.menu_filelist_move :
                mMenuMode = MENU_MODE_MOVE;
                mMenuCheckAll = false;
                mAdapter.fileCheckEnable(KFileListAdapter.MODE_CHECK);
                for(KFileListItem fileitem: mFileList) {
                    fileitem.setFileCheck(false);
                }
                mAdapter.notifyDataSetChanged();
            return true;

            case R.id.menu_filelist_delete :
                mMenuMode = MENU_MODE_DELETE;
                mMenuCheckAll = false;
                mAdapter.fileCheckEnable(KFileListAdapter.MODE_CHECK);
                for(KFileListItem fileitem: mFileList) {
                    fileitem.setFileCheck(false);
                }
                mAdapter.notifyDataSetChanged();
            return true;

            case R.id.menu_filelist_fileaction_select_all :
                mMenuCheckAll = !mMenuCheckAll;
                for(KFileListItem fileitem: mFileList) {
                    fileitem.setFileCheck(mMenuCheckAll);
                }
                mAdapter.notifyDataSetChanged();
            return true;

            case R.id.menu_filelist_fileaction_done :
            {
                if(mMenuMode == MENU_MODE_COPY) {
                    Intent intent = new Intent(this, KFileListDirectoryActivity.class);
                    intent.putExtra(KFileListDirectoryActivity.PATH, mCurrentpath);
                    startActivityForResult(intent, REQUEST_CODE_COPY);
                } else if(mMenuMode == MENU_MODE_MOVE) {
                    Intent intent = new Intent(this, KFileListDirectoryActivity.class);
                    intent.putExtra(KFileListDirectoryActivity.PATH, mCurrentpath);
                    startActivityForResult(intent, REQUEST_CODE_MOVE);
                } else if(mMenuMode == MENU_MODE_DELETE) {
                    createProgressDialog();
                }
            }
            return true;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
	public void onOptionsMenuClosed(Menu menu) {
        log.d("onOptionsMenuClosed mMenuMode = %d", mMenuMode);
    	menu.clear();
    	if(mMenuMode == MENU_MODE_LIST) {
    	    getMenuInflater().inflate(R.menu.activity_filelist, menu);
    	} else {
    	    getMenuInflater().inflate(R.menu.activity_filelist_fileaction, menu);
    	    mMenuDone = menu.findItem(R.id.menu_filelist_fileaction_done);
    	    mMenuDone.setEnabled(false);
    	}
	}

	@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        mContextMenuPos = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
        KFileListItem item = mAdapter.getItem(mContextMenuPos);
        if(item.getFileType() == KFileListItem.VIDEO || item.getFileType() == KFileListItem.PICTURE || item.getFileType() == KFileListItem.FILE) {
            getMenuInflater().inflate(R.menu.activity_filelist_context, menu);
            menu.setHeaderTitle(item.getName());
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        String path = mAdapter.getItem(mContextMenuPos).getPath();

        switch(item.getItemId()) {
            case R.id.menu_filelist_context_copy:
            log.i("onContextItemSelected : Copy / Path = ",path);
            KFileActionUtil.copy(mContext, path);
            return true;

            case R.id.menu_filelist_context_move :
            log.i("onContextItemSelected : Move");
            KFileActionUtil.move(mContext, path);
            return true;

            case R.id.menu_filelist_context_delete :
            log.i("onContextItemSelected : Delete");
            KFileActionUtil.delete(path, new KFileActionUtil.KFileActionUtilListener() {
                @Override
                public void onProgress(int time) {
                }

                @Override
                public void onError() {
                    mCurrentpath = makeFileList(mCurrentpath);
                }

                @Override
                public void onComplete() {
                    mCurrentpath = makeFileList(mCurrentpath);
                }
            });
            return true;

            case R.id.menu_filelist_context_rename :
            log.i("onContextItemSelected : Rename");
            return true;

            case R.id.menu_filelist_context_sharevia :
            log.i("onContextItemSelected : Share Via");
            return true;
        }

        return super.onContextItemSelected(item);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    KhFile khFile;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK) {
            log.d("onActivityResult RESULT_OK");
            switch(requestCode) {
                case REQUEST_CODE_COPY :
                    mMenuMode = MENU_MODE_LIST;
                    mAdapter.notifyDataSetChanged();
                    mAdapter.fileCheckEnable(KFileListAdapter.MODE_LIST);
                    mMenu.clear();
                    getMenuInflater().inflate(R.menu.activity_filelist, mMenu);

                    String copyDirectory = data.getExtras().getString(KFileListDirectoryActivity.RESULTS);
                    ArrayList<String> inputPath = new ArrayList<String>();
                    for(KFileListItem item : mFileList) {
                        if(item.getFileCheck()) {
                            inputPath.add(item.getPath());
                        }
                    }
                    mProgressDialog = KhProgressDialog.showStyleHorizontal(mContext, KhFile.pathToName((inputPath.get(0))), inputPath.size(),
                            new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    mProgressDialog.dismiss();
                                    mProgressDialog = null;
                                    mProgressDialog = KhProgressDialog.showStyleLarge(mContext);
                                    // cancel
                                    khFile.cancel();
                                }
                            });

//                    mHandler.sendEmptyMessageDelayed(0, 5000);
                    khFile = KhFile.copy(inputPath, copyDirectory, new KhFile.KhFileListener() {
                        @Override
                        public void onProgress(int progress) {
                            log.i("onProgress = %d", progress);
                            mProgressDialog.setTitle(String.format("prg = %s", progress));
                            mProgressDialog.setProgress(progress);
                        }

                        @Override
                        public void onComplete() {
                            log.i("onComplete");
                            mProgressDialog.dismiss();
                        }

                        @Override
                        public void onCancel() {
                            log.i("onCancel");
                            mProgressDialog.dismiss();
                        }

                        @Override
                        public void onError() {
                            log.i("onError");
                            mProgressDialog.dismiss();
                        }
                    });
                break;
            }
        }
    }

    private class OnFileCheckClickListenr implements KFileListCheckClickListener {
        @Override
        public void onFileCheckClick(boolean b) {
            log.e("OnFileCheckClickListenr "+b);
            if(b) {
                if(!mMenuDone.isEnabled()) {
                    mMenuDone.setEnabled(true);
                }
            } else {
                if(mMenuDone.isEnabled()) {
                    boolean check = true;
                    for(KFileListItem fileitem: mFileList) {
                        if(fileitem.getFileCheck()) {
                            check = false;
                            break;
                        }
                    }
                    if(check) mMenuDone.setEnabled(false);
                }
            }
        }
    }

    private class OnFileListItemClickListenr implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
            log.i("onItemClick %d",i);
            KFileListItem fileData = (KFileListItem) adapterview.getItemAtPosition(i);

            if(fileData.getFileType() == KFileListItem.FOLDERUP) {
                if(mCurrentpath.equals(mRoot)) {
                    finish();
                } else if(mCurrentpath.equals(mSdCard.getPath()) || (mExtsdCard == null ? false : mCurrentpath.equals(mExtsdCard.getPath()))) {
                    mCurrentpath = makeFileList(mRoot);
                } else {
                    char separatorChar = System.getProperty("file.separator", "/").charAt(0);
                    int separatorIndex = mCurrentpath.lastIndexOf(String.valueOf(separatorChar));

                    if(separatorIndex > 0)
                        mCurrentpath = makeFileList(mCurrentpath.substring(0, separatorIndex));
                }
            } else if(fileData.getFileType() == KFileListItem.FOLDER) {
                mCurrentpath = makeFileList(fileData.getPath());
            } else if(fileData.getFileType() == KFileListItem.VIDEO) {
                Intent intent = new Intent(mContext, KVideoEditActivity.class);
                intent.putExtra("path", fileData.getPath());
                startActivity(intent);
            } else if(fileData.getFileType() == KFileListItem.PICTURE) {
                Intent intent = new Intent(mContext, KImageEditActivity.class);
                intent.putExtra("path", fileData.getPath());
                startActivity(intent);
            }
        }
    }

    /* private */
    private void init() {
        mApplication = (KVideoCapture) getApplicationContext();
        mCurrentpath = mApplication.getCurrentPath();

        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.klist_file);
        mIconWidth = b.getWidth();
        mIconHeight = b.getHeight();
        b.recycle();

        mContext = this;
        mFileList = new ArrayList<KFileListItem>();
        mAdapter = new KFileListAdapter(this, mFileList, mIconWidth, mIconHeight, new OnFileCheckClickListenr());

        mListView = (ListView)findViewById(R.id.filelist_list);
        registerForContextMenu(mListView);

        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new OnFileListItemClickListenr());

        mProgressDialog = null;
    }

    private String makeFileList(String path) {
        String result = updateFileList(path);
        mApplication.setCurrentPath(mCurrentpath);
        mAdapter.notifyDataSetChanged();
        return result;
    }

    private String updateFileList(String path) {
        /* Storage directory */
        Map<String, File> externalLocations = KFileListExternalStorage.getAllStorageLocations();
        mSdCard = externalLocations.get(KFileListExternalStorage.SD_CARD);
        mExtsdCard = null;
        if(externalLocations.size() > 1) {
            mExtsdCard = externalLocations.get(KFileListExternalStorage.EXTERNAL_SD_CARD);
        }

        String currentpath = path;
        File[] files = new File(currentpath).listFiles();

        mFileList.clear();
        if(files == null) {
            mFileList.add(new KFileListItem("..", KFileListItem.FOLDERUP));
            return currentpath;
        } else if(path.equals(mRoot)) {
            mFileList.add(new KFileListItem(mSdCard.getPath(), KFileListItem.FOLDER));
            if(mExtsdCard != null) {
                mFileList.add(new KFileListItem(mExtsdCard.getPath(), KFileListItem.FOLDER));
            }
            return mRoot;
        }

        ArrayList<File> folderList = new ArrayList<File>();
        ArrayList<File> fileList = new ArrayList<File>();

        for(File file: files) {
            if(file.isDirectory()) {
                folderList.add(file);
            } else if(!file.isHidden()){
                fileList.add(file);
            }
        }

        /* up folder */
        mFileList.add(new KFileListItem("..", KFileListItem.FOLDERUP));

        for(int i = 0; i < folderList.size(); i++) {
            mFileList.add(new KFileListItem(folderList.get(i).getPath(), KFileListItem.FOLDER));
        }

        for(int i = 0; i < fileList.size(); i++) {
            mFileList.add(new KFileListItem(fileList.get(i).getPath(), KFileListItem.getFileType(fileList.get(i).getPath())));
        }
        return currentpath;
    }

    private void createProgressDialog() {
//        ProgressDialog.Builder progressDialogBuilder = new ProgressDialog.Builder(mContext);
//        KhProgressDialog.showStyleHorizontal(mContext, "123", null);
//        KhProgressDialog.showStyleLarge(mContext);
    }
}
